<!--
 * @Author: qwlbwm 18370818801qwl./
 * @Date: 2023-09-12 10:56:55
 * @LastEditors: whereamazinghappen 306702547@qq.com
 * @LastEditTime: 2023-10-26 11:37:36
 * @FilePath: \checc-business-module-web-kgpt-dev\src\views\examineManage\technologyExamine\zzExamine\examineDetail\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="container">
    <div class="index-title">{{ routeQuery.name }}</div>
    <el-row class="" style="margin-bottom: 20px">
      <el-col :span="16" align="left">
        <!-- <el-select
            v-model="searchFrom.status"
            style="width: 150px; margin-right: 15px"
            @change="search"
            placeholder="状态"
            size="small"
            clearable
          >
            <el-option
              v-for="item in state.dict_status_list"
              :key="item.itemValue"
              :label="item.itemText"
              :value="item.itemValue"
            >
            </el-option>
          </el-select>
          <el-button class="ordinary" @click="search()">搜索</el-button> -->
      </el-col>
      <el-col :span="8" align="right">
        <el-button
          class="ordinary"
          @click="getExportBtn()"
          v-limit="
            pageModel == 'self'
              ? 'KHGL:KJKH:ZZKJKH:BDWKHXQ:EXPORT'
              : 'KHGL:KJKH:ZZKJKH:KHXQ:EXPORT'
          "
          >批量导出</el-button
        >
      </el-col>
    </el-row>
    <div>
      <el-table
        :data="state.table_list"
        style="width: 100%"
        border
        row-key="id"
        ref="qwltTable"
        @selection-change="selectionChange"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
          :selectable="checkSelect"
          :reserve-selection="false"
        />
        <el-table-column prop="number" align="left" label="指标编号" width="150px" />
        <el-table-column prop="name" align="center" label="指标名称" />
        <el-table-column prop="scoreType_text" align="center" label="计分类型" width="80">
        </el-table-column>
        <el-table-column
          prop="scoreMethod_text"
          align="center"
          label="评分方式"
          width="80"
        >
        </el-table-column>
        <el-table-column prop="planScore" align="center" label="计划得分" width="100" />
        <el-table-column prop="finalScore" align="center" label="最终得分" width="100" />
        <el-table-column prop="systemScore" align="center" label="系统得分" width="80" />
        <el-table-column prop="selfScore" align="center" label="自评分" width="80">
          <template #default="scope">
            {{
              scope.row.myAnnualExamineIndexScore
                ? scope.row.myAnnualExamineIndexScore.selfScore
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column prop="manualScore" align="center" label="修订分" width="80">
          <template #default="scope">
            {{
              scope.row.myAnnualExamineIndexScore
                ? scope.row.myAnnualExamineIndexScore.manualScore
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column prop="manualReason" align="center" label="修订理由" width="80">
          <template #default="scope">
            {{
              scope.row.myAnnualExamineIndexScore
                ? scope.row.myAnnualExamineIndexScore.manualReason
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="selfPeopleUsername"
          align="center"
          label="自评人"
          width="80"
        >
          <template #default="scope">
            {{
              scope.row.myAnnualExamineIndexScore
                ? scope.row.myAnnualExamineIndexScore.selfPeopleUsername
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column prop="selfDatetime" align="center" label="自评时间" width="150">
          <template #default="scope">
            {{
              scope.row.myAnnualExamineIndexScore
                ? scope.row.myAnnualExamineIndexScore.selfDatetime
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="systemUpdateDatetime"
          align="center"
          label="系统得分更新时间"
          width="150"
        >
          <template #default="scope">
            {{
              scope.row.myAnnualExamineIndexScore
                ? scope.row.myAnnualExamineIndexScore.systemUpdateDatetime
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="manualPeopleUsername"
          align="center"
          label="修订人"
          width="80"
        >
          <template #default="scope">
            {{
              scope.row.myAnnualExamineIndexScore
                ? scope.row.myAnnualExamineIndexScore.manualPeopleUsername
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="manualDatetime"
          align="center"
          label="修订时间"
          width="150"
        >
          <template #default="scope">
            {{
              scope.row.myAnnualExamineIndexScore
                ? scope.row.myAnnualExamineIndexScore.manualDatetime
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" align="center" label="操作" width="150">
          <template #default="scope">
            <span v-if="scope.row.listType != 'sum'">
              <el-button
                type="primary"
                v-if="
                  scope.row.scoreMethod === '2' ||
                  (scope.row.scoreCompose && scope.row.scoreCompose.includes('A1000'))
                "
                v-limit="
                  pageModel == 'self'
                    ? 'KHGL:KJKH:ZZKJKH:BDWKHXQ:MANAGE'
                    : 'KHGL:KJKH:ZZKJKH:KHXQ:MANAGE'
                "
                @click="handleEdit(scope.row)"
                >管理</el-button
              >
              <el-button
                type="primary"
                @click="goIndexScore(scope.row)"
                v-limit="
                  pageModel == 'self'
                    ? 'KHGL:KJKH:ZZKJKH:BDWKHXQ:DETAIL'
                    : 'KHGL:KJKH:ZZKJKH:KHXQ:DETAIL'
                "
                v-if="scope.row.scoreMethod === '1' || scope.row.scoreSource == '01'"
                >明细</el-button
              >
            </span>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog
      v-model="state.editVisible"
      :close-on-click-modal="false"
      title="编辑"
      width="500px"
      @close="close"
    >
      <div class="examine-dialog-content">
        <el-form :model="myForm" ref="editFormRef" :rules="editRules" label-width="100px">
          <el-form-item label="指标名称:" prop="examineFactor">
            {{ myForm.name }}
          </el-form-item>
          <el-form-item label="自评分:" prop="selfScore">
            <el-input
              v-model="myForm.selfScore"
              type="number"
              placeholder="自评分"
              :disabled="pageModel == 'every'"
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="修订分:" v-if="pageModel == 'every'" prop="manualScore">
            <el-input
              v-model="myForm.manualScore"
              type="number"
              placeholder="修订分"
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="修订理由:" v-if="pageModel == 'every'" prop="manualReason">
            <el-input
              v-model="myForm.manualReason"
              :rows="2"
              type="textarea"
              placeholder="修订理由"
            />
          </el-form-item>
          <el-form-item label="质证依据:" prop="planScore">
            <el-upload
              ref="uploadRef"
              :action="state.uploadUrl"
              :headers="state.headers"
              :auto-upload="false"
              :on-success="onSuccess"
              :on-change="uploadChange"
              with-credentials
              multiple
              v-if="pageModel == 'self'"
            >
              <el-button type="primary">选择文件</el-button>
              <template #tip>
                <div class="el-upload__tip">文件大小单个上限200MB</div>
              </template>
            </el-upload>
            <div class="file-list" v-if="state.uploadFilelist.length">
              <div class="file-title">已上传文件</div>
              <div
                class="file-list-item"
                v-for="(item, index) in state.uploadFilelist"
                :key="index + 'qwl'"
              >
                <el-tooltip
                  class="box-item"
                  effect="dark"
                  :content="item.fileName"
                  placement="bottom-start"
                >
                  <span class="reupload-file-name">{{ item.fileName }}</span>
                </el-tooltip>
                <!-- {{ item.fileName }} -->
                <!-- <el-icon><Close /></el-icon> -->
                <i
                  class="el-icon-download qwl-icon"
                  v-if="pageModel == 'every'"
                  @click="downloadFile(item)"
                ></i>
                <i
                  class="el-icon-close qwl-icon"
                  v-if="pageModel == 'self'"
                  @click="handleDelete(item, index)"
                ></i>
              </div>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="state.editVisible = false">取消</el-button>
          <el-button type="primary" :loading="state.btnloading" @click="confirmEdit">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, nextTick } from "vue";
import { downloadByUrl } from '@/views/science/api/common'
// import Table from '../../../components/indexTable.vue'
import * as api from "../../../api/zJexaminePlan";
import { ElMessage } from "element-plus";
import { useRoute, useRouter } from "vue-router";
// import { deleteFileRequset } from "@/api/file";
import pubFc from "@/views/examineManage/utils";
// import { uploadFile } from '@/api/global'
interface Cdata {
  [propName: string]: any;
}
const searchFrom = reactive({
  //查询
  status: "",
});
// const refreshPage:any=inject('refreshPage', Function, true);
const editFormRef = ref();
const route = useRoute();
const router = useRouter();
const routeQuery = route.query;
// let annualId=route.query.id;
const pageModel = ref("");
pageModel.value =
  route.path == "/examineManage/techExamine/zzExamine/exSDetail" ? "self" : "every";
const uploadRef = ref();
const editRules = reactive({
  selfScore: [{ required: true, message: "请填写自评分", trigger: "blur" }],
});
let state = reactive<Cdata>({
  table_list: [],
  modalVisible: false,
  opType: "add", //add,edit,copy
  handleRowData: null, //正在处理的行数据
  table_loading: false,
  dict_status_list: [
    {
      itemValue: "1",
      itemText: "开启",
    },
    {
      itemValue: "2",
      itemText: "关闭",
    },
  ],
  planDetail: null,
  editVisible: false,
  simulateFjVisible: false,
  seletedFiles: [],
  uploadUrl: "/fastDfs/file/upload",
  headers: {
    Authorization: "Bearer " + localStorage.getItem("token"),
  },
  uploadIndex: 0,
  btnloading: false,
  uploadFilelist: [],
  seletedFileNum: 0,
});
const myForm: any = reactive({
  name: "",
  id: "",
  operateType: "1", //1自评2修订
  selfScore: "", //自评分
  manualScore: "",
  manualReason: "",
  basicAttachmentList: [],
});
let selectedRows = ref<any>([]);
// const search = () => {
//   //搜索
//   gettargetlist()
// }
const downloadFile = async (row) => {
  // api.downloadByUrl(row.fileId);
  await downloadByUrl(row.fileId, row.fileName)
  // api.downloadFileRequest(fileId)
  // let url = window.URL.createObjectURL(blob);
  // api
  //   .downloadFIleRequest({
  //     path: row.path,
  //   })
  //   .then((res) => {
  //     const { data, headers } = res
  //     const fileName = headers['content-disposition'].replace(/\w+;filename=(.*)/, '$1')
  //     const blob = new Blob([data as any], { type: headers['content-type'] })
  //     let dom = document.createElement('a')
  //     let url = window.URL.createObjectURL(blob)
  //     dom.href = url
  //     dom.download = decodeURI(fileName)
  //     dom.style.display = 'none'
  //     document.body.appendChild(dom)
  //     dom.click()
  //     dom.parentNode?.removeChild(dom)
  //     window.URL.revokeObjectURL(url)
  //   })
  // const a = document.createElement('a');
  //   a.href = row.path;
  //   a.download = row.fileName;
  //   a.click();
};
const handleDelete = (row, index) => {
  state.uploadFilelist.splice(index, 1);
  // deleteFileRequset(row.fileId).then((res) => {
  //   if (res.data.code == 200) {
  //     ElMessage.success('已删除')
  //   }
  // })
};
const onSuccess = (res, files) => {
  console.log('res',res);
  
  if(res.data){
    res.data.fileName = res.data.fileName.substring(0,50) + `.` + res.data.type
  }

  myForm.basicAttachmentList.push(res.data);
  state.uploadIndex++;
  if (state.uploadIndex >= state.seletedFileNum) {
    saveForm();
  }
  // state.seletedFiles = files
};
const uploadChange = (file, files) => {
  // state.seletedFiles = files
  console.log('files',files);
  
  state.seletedFiles = files;
  state.seletedFileNum = files.reduce((c, u) => c + (u.uid ? 1 : 0), 0);
};
const confirmEdit = () => {
  editFormRef.value?.validate((valid) => {
    if (valid) {
      state.btnloading = true;
      if (state.seletedFileNum !== 0) {
        uploadRef.value?.submit();
      } else {
        saveForm();
      }
    }
  });
};
const saveForm = () => {
  let params = JSON.parse(JSON.stringify(myForm));
  params.operateType = pageModel.value == "self" ? "1" : "2";
  if (params.operateType == "1") {
    delete params.manualScore;
    delete params.manualReason;
  }
  // params.basicAttachmentList = state.uploadFilelist.concat(params.basicAttachmentList);
  api
    .evaluateSaveRequest({
      ...params,
    })
    .then((res) => {
      state.btnloading = false;
      if (res.data.code == 200) {
        ElMessage.success("编辑成功");
        state.editVisible = false;
        gettargetlist();
      }
    });
};

const checkSelect = (row, index) => {
  let isChecked = true;
  if (index === 0) {
    // 判断里面是否存在某个参数
    isChecked = false;
  } else {
    isChecked = true;
  }
  return isChecked;
};

const getExportBtn = () => {
  //批量导出

  api
    .exportExDetailRequest({
      id: routeQuery.id, //ID
    })
    .then((res) => {
      const { data, headers } = res;
      pubFc.downloadFunc(data, headers);
    });
};
const selectionChange = (arr) => {
  //选中
  selectedRows.value = arr;
};

const handleEdit = (item) => {
  //评分管理
  //编辑
  state.uploadIndex = 0;
  state.seletedFiles = [];
  myForm.name = item.name;
  myForm.id = item.id;
  state.editVisible = true;
  state.seletedFileNum = 0;
  nextTick(() => {
    uploadRef.value?.clearFiles();
  });
  evaluateDetailRequest(item.id).then((res: any) => {
    myForm.selfScore = res.selfScore || "";
  });

  // myForm.selfScore=item.myAnnualExamineIndexScore?item.myAnnualExamineIndexScore.selfScore:'';
};
const evaluateDetailRequest = (id) => {
  return new Promise((resolve) => {
    api
      .evaluateDetailRequest({
        id: id,
      })
      .then((res) => {
        let response = res.data.data;
        state.uploadFilelist = response.basicAttachmentList.map((item) => {
          item.name = item.fileName;
          return item;
        });
        resolve(res.data.data);
      });
  });
};
const goIndexScore = (row) => {
  //前往明细页面
  let path =
    pageModel.value == "self"
      ? "/examineManage/techExamine/zzExamine/scoreLdetail"
      : "/examineManage/techExamine/zzExamine/scoreZdetail";
  router.push({
    path: path,
    query: {
      name: row.name,
      id: row.id,
    },
  });
};
const qwltTable = ref<any>();
const gettargetlist = () => {
  //获取table列表
  state.table_loading = true;
  api
    .examineDetailRequest({
      ...searchFrom,
      id: routeQuery.id, //1-中交标准指标、2-中咨标准指标
    })
    .then((res) => {
      state.table_loading = false;
      let list = res.data.data.produceItemIndexList;
      list.unshift({
        name: "合计",
        planScore: res.data.data.sumScore,
        finalScore: res.data.data.sumFinalScore,
        listType: "sum",
      });
      state.table_list = res.data.data.produceItemIndexList;
      nextTick(() => {
        if (qwltTable.value) {
          //使用了父子级后选中第一级再查询后这一级就无法清除了
          (qwltTable as any).value.clearSelection();
        }
      });
    });
};
const close = () =>{
  editFormRef.value.resetFields()
}
// getDictDatas()
gettargetlist();
</script>
<style lang="scss" scoped>
.container {
  background-color: white;
  padding: 20px;
  overflow-y: auto;
  .index-title {
    text-align: center;
    padding-bottom: 10px;
    border-bottom: 1px solid #e7e5e5;
    margin-bottom: 10px;
    font-size: 26px;
  }
}
.file-list {
  width: 100%;
  .file-title {
    color: #409eff;
  }
  .file-list-item {
    cursor: pointer;
    width: 350px;
    border-bottom: 1px solid #eeecec;
    position: relative;
    padding-right: 34px;

    .reupload-file-name {
      display: inline-block;
      width: 100%;
      text-overflow: ellipsis;
      overflow: hidden;
      white-space: nowrap;
      vertical-align: top;
    }
  }
  .el-icon-close {
    position: absolute;
    right: 10px;
    top: 5px;
    font-size: 18px;
  }
  .el-icon-download {
    position: absolute;
    right: 10px;
    top: 5px;
    font-size: 18px;
  }
  .qwl-icon:hover {
    color: #38b4da;
  }
  .file-list-item:hover {
    background: rgba(0, 0, 0, 0.1);
  }
}
.btnClass1 {
  color: #67c23a;
}
.btnClass2 {
  color: #f56c6c;
}
:deep(.el-dialog__body) {
  padding: 0;
}
:deep(.el-dialog__header) {
  border-bottom: 1px solid #f1eded;
}
:deep(.el-form-item__content) {
  flex-wrap: wrap;
}
:deep(.el-upload-list__item-name) {
  width: 303px;
}
</style>
